<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="ll.sms.util.ExtJsonBuilder"%>
<%@page import="ll.sms.util.SmsUtil"%>
<%@page import="ll.sms.util.AdminProperty"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>

		<title>消息发送监控</title>

		<meta http-equiv="pragma" content="no-cache">
		<meta http-equiv="cache-control" content="no-cache">
		<link rel="stylesheet" type="text/css" href="../ext/ext-all.css" />
		<script type="text/javascript" src="../ext/ext-base.js"></script>
		<script type="text/javascript" src="../ext/ext-all.js"></script>
		<script type="text/javascript" src="../js/copy.js"></script>
		<style type="text/css">
.ext-ie .x-menu-item-icon {
	left: -24px;
	top: 0px;
}

.ext-strict .x-menu-item-icon {
	left: 3px;
	top: 3px;
}

.ext-ie6 .x-menu-item-icon {
	left: -24px;
	top: 0px;
}

.settings {
	background: url(../img/excel.gif) left top no-repeat !important;
}

.blue-row .x-grid3-cell-inner {
	color: blue;
}

.red-row .x-grid3-cell-inner {
	color: red;
}

.green-row .x-grid3-cell-inner {
	color: green;
}

.cancel-red .x-grid3-cell-inner {
	color: #EBA56B;
}
.max-red .x-grid3-cell-inner {
	color: #8A8A00;
}
</style>
		<%
			String proxyString = ExtJsonBuilder.getAllProxyComboxString();
			String currentUser = SmsUtil.sessionHelper(session,
					AdminProperty.auname);
		%>
		<script type="text/javascript">
Ext.BLANK_IMAGE_URL = '../images/s.gif';
</script>
		<script type="text/javascript">
	window.onload = (function(){
		<%
		if(!"admin".equals(currentUser)){
		%>
		 function getproxytitle(){
		 return "-";
		 }
		 function getproxylist(){
		 return "-";
		 }
		<%}else{%>
		function getproxytitle(){

		return {text:'监控代理',id:'123456_0'};
		}
      function getproxylist(){
	  var store_showsize = new Ext.data.SimpleStore({
        fields: ['abbr', 'state'],
		data :<%=proxyString%>

    });
    var proxylist = new Ext.form.ComboBox({
        store: store_showsize,
        valueField:'abbr',
		displayField:'state',
        typeAhead: true,
        mode: 'local',
        name:'proxylist_',
        forceSelection: true,
        emptyText:'所有代理',
        id :'pl',
        hiddenName:'proxylist',
        triggerAction: 'all',
        selectOnFocus:true
    });
	return proxylist;
	}
	<%}%>


   var store_showsize = new Ext.data.SimpleStore({
        fields: ['abbr', 'state'],
		data :[['10','10'],['20','20'],['50','50'],['100','100'],['200','200'],['500','500']]
    });

    var showsize = new Ext.form.ComboBox({
        store: store_showsize,
        valueField:'abbr',
		displayField:'state',
        typeAhead: true,
        mode: 'local',
        name:'showsize_',
        forceSelection: true,
        emptyText:'10',
        id : 'sz',
        hiddenName : 'showsize',
        triggerAction: 'all',
        selectOnFocus:true
    });

	var AdminRecord = Ext.data.Record.create([
        {name: 'mid', type: 'string'},
        {name: 'mfrom', type: 'string'},
        {name: 'mto', type: 'string'},
        {name: 'mcontent', type: 'string'},
        {name: 'msendtime', type: 'string'},
        {name: 'maddtime', type: 'string'},
        {name: 'msendtype', type: 'int'},
        {name: 'mstatue', type: 'int'},
        {name: 'mchannel', type: 'string'}


    ]);

    var store = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({url: '../ajaxjsp/messagelist.jsp?newtimes='+new Date().getTime()}),
        reader: new Ext.data.JsonReader({
        totalProperty: 'totalCount',
        root: 'result'
        },AdminRecord),
        remoteSort: true
    });



    var columns = new Ext.grid.ColumnModel([
        new Ext.grid.RowNumberer(),
        {header: '发送状态', dataIndex: 'mstatue',width:60,align:'center',renderer: sendstatuset},
        {header: '发送者', dataIndex: 'mfrom'},
        {header: '接收者', dataIndex: 'mto'},
        {header: '内容', dataIndex: 'mcontent'},
        {header: '添加时间', dataIndex: 'maddtime'},
        {header: '发送类型', dataIndex: 'msendtype',renderer:function(val){return val==1?'单发':'群发';}},
        {header: '所走通道', dataIndex: 'mchannel'},
        {header: '默认发送时间', dataIndex: 'msendtime'}

    ]);
        columns.defaultSortable = false;
        function sendstatuset(value,e){

			if(value == 0){
				//wait
				return "<img src=\"../img/wait.gif\" alt=\"等待队列\"/>";
			}else if(value == 1){
				//success
				return "<img src=\"../img/suc.gif\" alt=\"发送成功\"/>";
			}else if(value == -1){
				//cancel
				return "<img src=\"../img/cancle.gif\" alt=\"取消发送\"/>";
			}else if(value == -2){
				//error
				return "<img src=\"../img/fail.gif\" alt=\"发送失败\"/>";
			}else if(value == -3){
				//error
				return "<img src=\"../img/proxycacel.gif\" alt=\"取消发送\"/>";
			}else if(value == -4){
				//max error
				return "<img src=\"../images/warning.gif\" alt=\"超过最大值发送\"/>";
			}else{
			return value;
			}
        }
        var grid = new Ext.grid.GridPanel({
        title: '消息监控',
        region: 'center',
        loadMask: true,
        store: store,
        cm: columns,
        sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
        viewConfig: {
        columnsText:'显示的列',
        sortAscText:'升序',
        sortDescText:'降序',
        forceFit: true
        }
       ,
        bbar: new Ext.PagingToolbar({
            pageSize: 1000,
            store: store,
            displayInfo: true,
            displayMsg: '显示 {2} 条记录',
            emptyMsg:'没有记录'

        }),
        tbar: new Ext.Toolbar({
 			items:[getproxytitle(),getproxylist(),'-',{text:'监控条数',id:'123'},showsize,'->',

 			      {
 	 			id : 'pause',
 	 			text : '<div id=\"showtaskflag\">暂停</div>',
 	 			handler: function(){
 						taskPause();
 	           		}
 	 			},
		 	{
 			id : 'exportexcel',
 			iconCls:'settings',
 			text : '导出excel',
 			handler: function(){
	 			var _pl_;
				if(typeof(Ext.getCmp('pl'))=='undefined'){
					_pl_ = '';
				}else{
					_pl_ = Ext.getCmp('pl').getValue();
				}
                  var url = "getexcel_monitor.jsp?showsize="+Ext.getCmp('sz').getValue()+"&proxyid="+_pl_+"&flag="+new Date().getTime();
            	  window.open (url, 'newwindow', 'height=100, width=400, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=n o, status=no')
           		}
 			}]
        })
    });

     grid.getView().getRowClass = function(record, index){
     		var value = record.data.mstatue;
    		if(value == 0){
				//wait
				return "";
			}else if(value == 1){
				//success
				return  'green-row';
			}else if(value == -1){
				//cancel
				return 'blue-row';
			}else if(value == -2){
				//error
				return 'red-row';
			}else if(value == -3){
				return 'cancel-red';
			}else if(value == -4){
				return 'max-red';
			}else{
			return "";
			}


     };

     grid.on("cellclick",function(grid, rowIndex, columnIndex, e)
        {
        /*
         var node = e.target;
         while(node.tagName != 'TR'){
             node = node.parentNode;
            if(node.tagName == 'TR'){
                 break;
             }
         }
         var elDiv = node.parentNode.parentNode.parentNode.parentNode;
         for(var i = 0; i<elDiv.childNodes.length;i++){
             elDiv.childNodes[i].childNodes[0].childNodes[0].childNodes[0].style.cssText="background-color:";
         }
         node.style.cssText="background-color:#FAE0CF";
		*/
            e.preventDefault();if(rowIndex<0){return;}
            var record = grid.getStore().getAt(rowIndex);   //Get the Record
			var fieldName = grid.getColumnModel().getDataIndex(columnIndex); //Get field name
			var data = record.get(fieldName);
			if(fieldName=='mstatue'){
			if(data==0){ //只有待发送的消息才能被取消
			 var treeMenu = new Ext.menu.Menu
            ([
                {xtype:"button",text:"取消发送",icon:"../img/copy.gif",pressed:true,handler:function(){
				var sendtime = record.get('msendtime');
				var timeslong = Date.parseDate(sendtime , "Y-m-d H:i:s").getTime();
					if((timeslong - new Date().getTime())/1000 <30){
						alert("不能终止在30秒内即将发送的消息！");
					}else{

						  Ext.Ajax.request({
		                  url : '../ajaxjsp/cancelmessage_proxy.jsp',
		                  method : 'POST',
		                  params : {
		                      messageId:record.get('mid')
		                  },
		                  success: function(response, options) {
		                        //获取响应的json字符串
		                       var responseArray = Ext.util.JSON.decode(response.responseText);
		                            if(responseArray.success==true){
		                                 record.set('mstatue',"<img src=\"../img/proxycacel.gif\" alt=\"取消发送\"/>");
										 alert('操作成功');
		                            }
		                            else{
		                               	alert('操作失败');
		                            }
		                         }
		              		});
					}



                }}
            ]);
            treeMenu.showAt(e.getPoint());
			}
			return;
			}
            var treeMenu = new Ext.menu.Menu
            ([
                {xtype:"button",text:"复制到剪贴板",icon:"../img/copy.gif",pressed:true,handler:function(){
	                if(Ext.isIE){
	                	if(fieldName=='mto'){
			                copy_clip(data.replace(/,/g,'\n'));
    		                }else{
    		                copy_clip(data);
        		            }
		                alert('['+data+']已经复制到剪贴板');
	                }else{
	                	alert('对不起,剪贴板只支持IE浏览器复制!!');
	                }
                }}
            ]);
            treeMenu.showAt(e.getPoint());
        });


   
	store.on('beforeload',function(){
	 var _pl_;
	if(typeof(Ext.getCmp('pl'))=='undefined'){
		_pl_ = '';
	}else{
		_pl_ = Ext.getCmp('pl').getValue();
	}
          Ext.apply(
          this.baseParams,
          {
              pl:_pl_,
			  sz :Ext.getCmp('sz').getValue()
          });
     });
    store.load({params:{start:0,limit:1000}});
	var viewport = new Ext.Viewport({
	renderTo:'mt',
	layout:'border',
	items:[grid]
	});


//----定时任务----
		var task = {
			run : function(){
			store.reload({params:{start:0,limit:1000}});
			},
			interval : 10000
		};

		var taskRunner = new Ext.util.TaskRunner();
		taskRunner.start(task);

		function taskPause(){
			var value = document.getElementById('taskflag').value;
			if('runninghihi'==value){
				//pause
				taskRunner.stop(task);
				
				document.getElementById('showtaskflag').innerHTML='取消暂停';
				document.getElementById('taskflag').value='stopwuwu';
			}
			if('stopwuwu'==value){
				//cancel pause
				taskRunner.start(task);
				document.getElementById('showtaskflag').innerHTML='暂停';
				document.getElementById('taskflag').value='runninghihi';
			}
			
		}
	});
	</script>
	</head>

	<body>
		<div id="mt"></div>
		<div id="north"></div>
		<div id="south"></div>
		<div id="wait" align="center"></div>
		<div id="east"></div>
		<div id="west"></div>
		<div id="timetypediv"></div>
		<input value="runninghihi" id="taskflag" type="hidden"/>
		<input value="sdasdasd" id="ddd" type="button"/>
	</body>
</html>
